﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

namespace QuangMobile.Admin
{
    public partial class DangSanPham : System.Web.UI.Page
    {
        private static int IDSanPham;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadListSanPham();
                LoadHangSP(ddlHangSanXuat);
                MultiView1.ActiveViewIndex = 1;
            }
        }

        protected void LoadListSanPham()
        {
            string sql = "SELECT * FROM dbo.tblWebSanPham ORDER BY UpdateDate DESC";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            grvData.DataSource = dt;
            grvData.DataBind();
        }

        protected void LoadListSanPham(int hang)
        {
            string sql = "SELECT * FROM dbo.tblWebSanPham WHERE HangID_DM = @HangID_DM OR @HangID_DM = -1 ORDER BY UpdateDate DESC";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@HangID_DM", SqlDbType.Int, ParameterDirection.Input, hang));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            grvData.DataSource = dt;
            grvData.DataBind();
        }

        protected void SuaSanPham()
        {
            string sql = "";
            List<SqlParameter> arrParams = new List<SqlParameter>();

            string querry = "";
            if (txtAnhSP.HasFile)
            {
                querry += "AnhSP=@AnhSP,";
                arrParams.Add(SqlHelper.CreateParameterObject("@AnhSP", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile()));
            }
            if (!txtMoTa.Text.Trim().Equals(""))
            {
                querry += "MoTa=@MoTa,";
                arrParams.Add(SqlHelper.CreateParameterObject("@MoTa", SqlDbType.NVarChar, ParameterDirection.Input, txtMoTa.Text));
            }
            if (!txtKichThuoc.Text.Trim().Equals(""))
            {
                querry += "KichThuoc=@KichThuoc,";
                arrParams.Add(SqlHelper.CreateParameterObject("@KichThuoc", SqlDbType.NVarChar, ParameterDirection.Input, txtKichThuoc.Text));
            }
            if (!txtTrongLuong.Text.Trim().Equals(""))
            {
                querry += "TrongLuong=@TrongLuong,";
                arrParams.Add(SqlHelper.CreateParameterObject("@TrongLuong", SqlDbType.NVarChar, ParameterDirection.Input, txtTrongLuong.Text));
            }
            if (!txtBaoHanh.Text.Trim().Equals(""))
            {
                querry += "BaoHanh=@BaoHanh,";
                arrParams.Add(SqlHelper.CreateParameterObject("@BaoHanh", SqlDbType.NVarChar, ParameterDirection.Input, txtBaoHanh.Text));
            }
            sql += "UPDATE dbo.tblWebSanPham SET HangID_DM=@HangID_DM,NhomID_DM=@NhomID_DM,TenSP=@TenSP,GiaSP=@GiaSP," + querry + "PhuKien=@PhuKien,KhuyenMai=@KhuyenMai,GhiChu=@GhiChu,UpdateDate=GETDATE(),UserID=@UserID WHERE ID=@ID";

            arrParams.Add(SqlHelper.CreateParameterObject("@HangID_DM", SqlDbType.Int, ParameterDirection.Input, cboHangSanXuat.SelectedValue));
            arrParams.Add(SqlHelper.CreateParameterObject("@NhomID_DM", SqlDbType.Int, ParameterDirection.Input, cboNhomSanPham.SelectedValue));
            arrParams.Add(SqlHelper.CreateParameterObject("@TenSP", SqlDbType.NVarChar, ParameterDirection.Input, txtTenSP.Text));
            arrParams.Add(SqlHelper.CreateParameterObject("@GiaSP", SqlDbType.Float, ParameterDirection.Input, Convert.ToDouble(txtGiaSP.Text)));
            arrParams.Add(SqlHelper.CreateParameterObject("@PhuKien", SqlDbType.NVarChar, ParameterDirection.Input, txtPhuKien.Text));
            arrParams.Add(SqlHelper.CreateParameterObject("@KhuyenMai", SqlDbType.NVarChar, ParameterDirection.Input, txtKhuyenMai.Text));
            arrParams.Add(SqlHelper.CreateParameterObject("@GhiChu", SqlDbType.NVarChar, ParameterDirection.Input, txtGhiChu.Value));
            arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["UserID"]));
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, IDSanPham));
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
        }

        protected void ThemSanPham()
        {
            string sql = "";
            List<SqlParameter> arrParams = new List<SqlParameter>();

            string querry = "";
            string param = "";
            if (txtAnhSP.HasFile)
            {
                querry += "AnhSP,";
                param += "@AnhSP,";
                arrParams.Add(SqlHelper.CreateParameterObject("@AnhSP", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile()));
            }
            if (!txtMoTa.Text.Trim().Equals(""))
            {
                querry += "MoTa,";
                param += "@MoTa,";
                arrParams.Add(SqlHelper.CreateParameterObject("@MoTa", SqlDbType.NVarChar, ParameterDirection.Input, txtMoTa.Text));
            }
            if (!txtKichThuoc.Text.Trim().Equals(""))
            {
                querry += "KichThuoc,";
                param += "@KichThuoc,";
                arrParams.Add(SqlHelper.CreateParameterObject("@KichThuoc", SqlDbType.NVarChar, ParameterDirection.Input, txtKichThuoc.Text));
            }
            if (!txtTrongLuong.Text.Trim().Equals(""))
            {
                querry += "TrongLuong,";
                param += "@TrongLuong,";
                arrParams.Add(SqlHelper.CreateParameterObject("@TrongLuong", SqlDbType.NVarChar, ParameterDirection.Input, txtTrongLuong.Text));
            }
            if (!txtBaoHanh.Text.Trim().Equals(""))
            {
                querry += "BaoHanh,";
                param += "@BaoHanh,";
                arrParams.Add(SqlHelper.CreateParameterObject("@BaoHanh", SqlDbType.NVarChar, ParameterDirection.Input, txtBaoHanh.Text));
            }
            sql += "INSERT INTO dbo.tblWebSanPham( HangID_DM ,NhomID_DM ,TenSP ,GiaSP ," + querry + "PhuKien ,KhuyenMai ,GhiChu ,CreateDate ,UpdateDate ,UserID)";
            sql += "VALUES (@HangID_DM ,@NhomID_DM ,@TenSP ,@GiaSP ," + param + "@PhuKien ,@KhuyenMai ,@GhiChu ,GETDATE(),GETDATE(),@UserID)";

            arrParams.Add(SqlHelper.CreateParameterObject("@HangID_DM", SqlDbType.Int, ParameterDirection.Input, cboHangSanXuat.SelectedValue));
            arrParams.Add(SqlHelper.CreateParameterObject("@NhomID_DM", SqlDbType.Int, ParameterDirection.Input, cboNhomSanPham.SelectedValue));
            arrParams.Add(SqlHelper.CreateParameterObject("@TenSP", SqlDbType.NVarChar, ParameterDirection.Input, txtTenSP.Text));
            arrParams.Add(SqlHelper.CreateParameterObject("@GiaSP", SqlDbType.Float, ParameterDirection.Input, Convert.ToDouble(txtGiaSP.Text)));
            arrParams.Add(SqlHelper.CreateParameterObject("@PhuKien", SqlDbType.NVarChar, ParameterDirection.Input, txtPhuKien.Text));
            arrParams.Add(SqlHelper.CreateParameterObject("@KhuyenMai", SqlDbType.NVarChar, ParameterDirection.Input, txtKhuyenMai.Text));
            arrParams.Add(SqlHelper.CreateParameterObject("@GhiChu", SqlDbType.NVarChar, ParameterDirection.Input, txtGhiChu.Value));
            arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["UserID"]));
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string sID = e.CommandArgument.ToString().Trim();
            string sCommandName = e.CommandName;

            if ((sCommandName == QuangMobile.MyConst.Action.Approve))
            {
                btnLuu.CommandName = MyConst.Action.Approve;
                MultiView1.ActiveViewIndex = 0;
                LoadHangSP(cboHangSanXuat);
                LoadNhomSP();
                LoadChiTietSanPham(Convert.ToInt32(sID));
                IDSanPham = Convert.ToInt32(sID);
            }
            if ((sCommandName == MyConst.Action.Delete))
            {
                string sql = "DELETE FROM dbo.tblWebSanPham WHERE ID = " + sID;
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql);
            }
            grvData.EditIndex = -1;
            LoadListSanPham();
        }

        private void LoadChiTietSanPham(int sID)
        {
            string sql = "SELECT * FROM dbo.tblWebSanPham WHERE ID = " + sID;
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            txtTenSP.Text = dt.Rows[0]["TenSP"].ToString();
            if (dt.Rows[0]["AnhSP"] == DBNull.Value)
            {
                imgAnhSP.ImageUrl = "../upload/no-image.png";
            }
            else
            {
                imgAnhSP.ImageUrl = "../" + dt.Rows[0]["AnhSP"].ToString();
            }
            cboHangSanXuat.SelectedValue = (dt.Rows[0]["HangID_DM"].ToString());
            cboNhomSanPham.SelectedValue = (dt.Rows[0]["NhomID_DM"].ToString());
            txtGiaSP.Text = dt.Rows[0]["GiaSP"].ToString();
            txtMoTa.Text = dt.Rows[0]["MoTa"].ToString();
            txtKichThuoc.Text = dt.Rows[0]["KichThuoc"].ToString();
            txtTrongLuong.Text = dt.Rows[0]["TrongLuong"].ToString();
            txtBaoHanh.Text = dt.Rows[0]["BaoHanh"].ToString();
            txtPhuKien.Text = dt.Rows[0]["PhuKien"].ToString();
            txtKhuyenMai.Text = dt.Rows[0]["KhuyenMai"].ToString();
            txtGhiChu.Value = dt.Rows[0]["GhiChu"].ToString();
        }

        protected void grvData_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvData.EditIndex = e.NewEditIndex;
            LoadListSanPham();
        }

        protected void grvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvData.EditIndex = -1;
            LoadListSanPham();
        }

        protected void grvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            grvData.DeleteRow(e.RowIndex);
            grvData.DataBind();
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            if (btnLuu.CommandName == MyConst.Action.Addnew)
            {
                ThemSanPham();
            }
            else
            {
                SuaSanPham();
            }
            LoadListSanPham();
            MultiView1.ActiveViewIndex = 1;
        }

        protected void btnThemMoi_Click(object sender, EventArgs e)
        {
            btnLuu.CommandName = MyConst.Action.Addnew;
            MultiView1.ActiveViewIndex = 0;
            LoadHangSP(cboHangSanXuat);
            LoadNhomSP();
            ClearField();
        }

        private void ClearField()
        {
            txtTenSP.Text = "";
            cboHangSanXuat.SelectedValue = "-1";
            cboNhomSanPham.SelectedValue = "-1";
            txtGiaSP.Text = "";
            txtMoTa.Text = "";
            txtKichThuoc.Text = "";
            txtTrongLuong.Text = "";
            txtBaoHanh.Text = "";
            txtPhuKien.Text = "";
            txtKhuyenMai.Text = "";
            txtGhiChu.Value = "";
            imgAnhSP.ImageUrl = "";
        }

        protected void LoadHangSP(DropDownList ddl)
        {
            string sql = "SELECT * FROM dbo.tblWebDanhMuc WHERE MaDM = 'sp'";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            ddl.DataSource = dt;
            ddl.DataTextField = "TenDM";
            ddl.DataValueField = "ID";
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("Chọn hãng sản xuất", "-1"));
        }
        protected void LoadNhomSP()
        {
            string sql = "SELECT * FROM dbo.tblWebDanhMuc WHERE MaDM = 'nhom'";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            cboNhomSanPham.DataSource = dt;
            cboNhomSanPham.DataTextField = "TenDM";
            cboNhomSanPham.DataValueField = "ID";
            cboNhomSanPham.DataBind();
            cboNhomSanPham.Items.Insert(0, new ListItem("Chọn nhóm sản phẩm", "-1"));
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            ClearField();
            MultiView1.ActiveViewIndex = 1;
        }

        private string UploadFile()
        {
            try
            {
                if (txtAnhSP.HasFile)
                {
                    string sFolderPath = Server.MapPath(@"../upload/");
                    HttpPostedFile myFile = txtAnhSP.PostedFile;
                    string sFileName = myFile.FileName;
                    string[] arrFileName = sFileName.Split('.');
                    arrFileName[0] = DateTime.Now.ToString("ddMMyyhhssmm");
                    sFileName = arrFileName[0] + "." + arrFileName[1];
                    myFile.SaveAs(string.Format(@"{0}\{1}", sFolderPath, sFileName));
                    return "upload/" + sFileName;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {
                return "";
            }
        }

        protected void grvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvData.PageIndex = e.NewPageIndex;
            grvData.DataBind();
        }

        protected void ddlHangSanXuat_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadListSanPham(Convert.ToInt32(ddlHangSanXuat.SelectedValue));
        }
    }
}
